package cn.yh.nft.turbo.user.infrastructure.interceptor;

import cn.yh.nft.turbo.api.user.response.data.UserInfo;
import cn.yh.nft.turbo.user.domain.entity.User;
import cn.yh.nft.turbo.user.domain.entity.convertor.UserConvertor;
import cn.yh.nft.turbo.web.vo.Result;
import com.github.houbb.sensitive.core.api.SensitiveUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @ClassName: SensitiveResponseBodyAdvice
 * @Author: 草莓爱上啵啵
 *
 * 脱敏响应体处理
 */

@ControllerAdvice
public class SensitiveResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        //只对特定类型的返回值执行处理逻辑，这里可以根据需要调整判断条件
        return Result.class.isAssignableFrom(returnType.getParameterType());
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //如果返回的对象是UserInfo,进行脱敏处理
        //// 1. 检查返回的对象是否是Result类型，并且Result中的data是UserInfo类型
        if (body instanceof Result && ((Result<?> )body).getData() instanceof UserInfo){
            // 2. 将返回的对象强制转换为Result<UserInfo>类型
            Result<UserInfo> result = (Result<UserInfo>) body;

            // 3. 从Result对象中获取UserInfo数据
            UserInfo userInfo = result.getData();

            // 4. 使用UserConvertor将UserInfo对象转换为User实体对象
            User user = UserConvertor.INSTANCE.mapToEntity(userInfo);
            // 5. 对User对象进行脱敏处理
            user = SensitiveUtil.desCopy(user);

            // 6. 将脱敏后的User对象转换回UserInfo对象
            result.setData(UserConvertor.INSTANCE.mapToVo(user));

            return result;
        }

        return body;
    }
}
